<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <el-form-item label="商品类目：">
            <el-input v-model="filters.orgNumber" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="商户名称：">
            <el-input v-model="filters.name" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="商户code：">
            <el-input v-model="filters.thirdMerchantCode" placeholder=" " clearable></el-input>
          </el-form-item>
          <el-form-item prop="contactName" label="联系人">
            <el-input v-model="filters.contactName" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="联系人手机：">
            <el-input v-model="filters.contactMobile" placeholder="" clearable></el-input>
          </el-form-item>
        </el-row>
        <el-row class="search-button">
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-refresh"
              :label="$t('action.reset')"
              type="primary"
              @click="resetForm('filters')"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              :label="$t('action.add')"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="reviewStatus">批量审核</el-button>
          </el-form-item>
        </el-row>
        <!-- <el-form-item>
            <kt-button icon="fa fa-plus" label="审核" type="primary" @click="handleAdd"/>
        </el-form-item>-->
        <el-form-item class="t_r w100">
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o" @click="downloadExcel"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
        <table-column-filter-dialog
          ref="tableColumnFilterDialog"
          :columns="columns"
          @handleFilterColumns="handleFilterColumns"
        ></table-column-filter-dialog>
      </el-form>
    </div>
    <!--表格内容栏-->
    <div class="tab-container">
      <!-- tbs标签 -->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane v-for="item in tabMapOptions" :key="item.key" :label="item.label" :name="item.key">
        </el-tab-pane>
      </el-tabs>
      <!-- jic table表格-->
      <div class="toolbar" >
        <!--表格显示列界面-->
        <table-column-filter-dialog
          ref="tableColumnFilterDialog"
          :columns="columns"
          @handleFilterColumns="handleFilterColumns"
        ></table-column-filter-dialog>
      </div>
      <!--表格内容栏-->
      <jic-table
        ref="JicTable"
        :data="pageResult"
        :operationWidth="390"
        :totalSize="totalSize"
        :columns="filterColumns"
        :showCopyDataOperation="true"
        :showCopyLinkOperation="false"
        :showDetailOperation="true"
        :showBatchDelete="false"
        :loading="loading"
        :btnList="btnList"
        @findPage="findPage"
        @handleEdit="handleEdit"
        @handleDetail="handleDetail"
        ></jic-table>
    </div>
    <!--新增编辑界面-->
    <el-dialog
      title="添加商户"
      width="50%"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
      @closed="handleClose"
    >
      <el-form
        :model="dataForm"
        label-width="110px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-row class="searchDialog-input">
          <el-form-item label="商户分类：" prop="merchantType">
            <el-select v-model="dataForm.merchantType" style="width:100%;">
              <el-option label="自营" value="1">自营</el-option>
              <el-option label="第三方入驻商户" value="2">第三方入驻商户</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商户编码：" prop="orgNumber">
            <el-input
              v-model="dataForm.orgNumber"
              auto-complete="off"
              :disabled="false"
              placeholder="请输入商户编码"
            ></el-input>
          </el-form-item>
          <el-form-item label="商户名称：" prop="name">
            <el-input
              v-model="dataForm.name"
              auto-complete="off"
              :disabled="false"
              placeholder="请输入商户名称"
            ></el-input>
          </el-form-item>
          <!--<el-form-item label="所属组织：" prop="deptId">-->
            <!--<el-select-->
              <!--v-model="dataForm.deptId"-->
              <!--placeholder="所属组织"-->
              <!--style="width:100%;"-->
              <!--@change="queryRoleList(dataForm.deptId)"-->
            <!--&gt;-->
              <!--<el-option-->
                <!--v-for="(item,index) in deptList"-->
                <!--:key="index"-->
                <!--:label="item.deptName"-->
                <!--:value="item.id"-->
              <!--&gt;</el-option>-->
            <!--</el-select>-->
          <!--</el-form-item>-->
          <el-form-item label="账号：" prop="account">
            <el-input v-model="dataForm.account" auto-complete="off" :disabled="false" placeholder="请输入账号"></el-input>
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input
              v-model="dataForm.password"
              auto-complete="off"
              :disabled="false"
              show-password
              maxlength="18"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <el-select v-model="dataForm.roleId" style="width:100%;" placeholder="请选择">
              <el-option
                v-for="(item,index) in roleList"
                :key="index"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="dataForm.contactName" auto-complete="off" :disabled="false" placeholder="请输入联系人"></el-input>
          </el-form-item>
          <el-form-item label="联系人手机" prop="contactMobile">
            <el-input
              v-model="dataForm.contactMobile"
              auto-complete="off"
              :disabled="false"
              maxlength="11"
              oninput="value=value.replace(/[^\d]/g,'')"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
    <!--审核界面-->
    <el-dialog
      title="入驻商户审核"
      width="30%"
      :visible.sync="reviewFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="reviewForm"
        label-width="100px"
        :rules="reviewFormRules"
        ref="reviewForm"
        :size="size"
      >
        <el-row class="searchDialog-input">
          <el-form-item label="审核状态：" class="styleReplace2" prop="status">
          <el-select v-model="reviewForm.status" style="width:100%">
            <el-option label="审核通过" value="2">审核通过</el-option>
            <el-option label="审核拒绝" value="3">审核拒绝</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" class="reviewReason" prop="reviewReason">
          <el-input v-model="reviewForm.reviewReason" auto-complete="off" placeholder="请输入备注"></el-input>
        </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="reviewFormVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="reviewSuccess"
          :loading="editLoading"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportExcel } from "@/utils/excel";
// import CyTable from "@/views/Core/JicTable";
import JicTable from "./MerchantTbale";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import {
  validatePhone,
  validateContacts,
  isEmail,
  isNumber
} from "@/utils/validate";

export default {
  components: {
    JicTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    var account = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("账号为必填"));
      } else if (value.length < 1 || value.length > 30) {
        return callback(new Error("账号为1-30字符"));
      } else if (value == " ") {
        return callback(new Error("账号不可为纯空格"));
      } else if (/\s/.test(value)) {
        return callback(new Error("账号不可含有纯空格"));
      } else if (!/^[\u4e00-\u9fa5_a-zA-Z0-9]+$/.test(value)) {
        return callback(new Error("账号不可为纯符号"));
      } else {
        callback();
      }
    };
    return {
      tabMapOptions: [
        { label: "全部", key: "99" },
        { label: "待提交 0", key: "991" },
        { label: "待审核 0", key: "992" },
        { label: "审核通过 0", key: "993" },
        { label: "审核不通过", key: "994" },
      ],
      activeName: "0",
      //列表按钮
      btnList: [{
          customLabel: "查看",
          isShowMethod: "1,2,3,4",
          method: "handleDetail",
          perms: "sys:role:add"
      },{
          customLabel: "编辑",
          isShowMethod: "1,3,4",
          method: "handleEdit",
          perms: "sys:role:add"
      }, {
          customLabel: "删除",
          isShowMethod: "1,3,4",
          method: "deleteLottery",
          perms: "sys:role:add"
      }, {
          customLabel: "提交审核",
          isShowMethod: "1,4",
          method: "deleteLottery",
          perms: "sys:role:add"
      }, {
          customLabel: "审核",
          isShowMethod: "2",
          method: "deleteLottery",
          perms: "sys:role:add"
      }],
      
      totalSize:0,
      
      loading:true,
      content: "",
      size: "small",
      filters: {
        status: '',
      },
      columns: [
        { prop: "name", label: "商户名称", minWidth: 120 },
        { prop: "thirdMerchantCode", label: "商户code", minWidth: 120 },
        { prop: "merchantType", label: "类目编码", minWidth: 120,},
        { prop: "merchantType", label: "商品类目", minWidth: 120,},
        { prop: "merchantType", label: "平台标准扣点", minWidth: 120,},
        { prop: "merchantType", label: "类目扣点", minWidth: 120,},
        { prop: "merchantType", label: "申请时间", minWidth: 120,},
        {
          prop: "status",
          label: "审核状态",
          minWidth: 120,
          formatter: this.statusFormatter
        },
      ],
      filterColumns: [],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: {},

      dataFormRules: {
        orgNumber: [
          { required: true, message: "请输入商户编码", trigger: "blur" }
        ],
        name: [
          { required: true, validator: validateContacts, trigger: "blur" }
        ],
        merchantType: [
          { required: true, message: "请选择商户类型", trigger: "change" }
        ],
        // deptId: [
        //   { required: true, message: "请选择所属组织", trigger: "change" }
        // ],
        roleId: [
          { required: true, message: "请选择账号角色", trigger: "change" }
        ],
        account: [{ required: true, validator: account, trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        contactName: [
          { required: true, validator: validateContacts, trigger: "blur" }
        ],
        contactMobile: [
          { required: true, validator: validatePhone, trigger: "blur" }
        ]
      },

      operation: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      editLoading: false,
      reviewFormRules: {
        status: [
          { required: true, message: "请选择审核状态", trigger: "change" }
        ],
        replyContent: [{ required: true, message: "回复内容", trigger: "blur" }]
      },
      // 新增编辑界面数据
      dataForm: {
        orgNumber: "",
        name: "",
        merchantType: "",
        // account: "",
        // password: "",
        // roleId: "",
        // deptId: "",
        contactName: "",
        contactMobile: ""
      },
      reviewForm: {
        reviewReason: "",
        status: ""
      },
      checked: [],
      reviewFormVisible: false,
      shopList: [],
      statusList: [],
      deptList: [], //部门列表
      roleList: []
    };
  },
  
  watch: {
    activeName(val) {
      if(val != '0'){
        this.filters.status = val;
      }else{
        this.filters.status = null;
      }
      this.findPage();
    }

  },
  created() {
    // init the default selected tab
    const tab = this.$route.query.tab
    if (tab) {
      this.activeName = tab
    }
  },
  methods: {
    // 获取分页数据
    findPage: function(data) {
      if (data != null && data.start != null) {
        if (data.start != null) {
          this.pageRequest.pageNum = data.start;
        }
        if (data.limit != null) {
          this.pageRequest.pageSize = data.limit;
        }
      }
      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = this.pageRequest.pageNum;
      this_.filters.limit = this.pageRequest.pageSize;
      this.utils.request.queryMerchantList(this_.filters, function(res) {
        if (res.data == null) {
          this_.loading = false;
          res.data = [];
          res.totle = 0;
        } else {
          this_.loading = false;
          this_.$refs.JicTable.findPage({
            content: res.data.rows,
            total: res.data.total
          });
        }
      });
    },
    //获取组织结构
    getDeptListByType() {
      var that = this;
      this.utils.request.queryDeptList({ deptType: 2 }, res => {
        if (res.code == "0000") {
          that.deptList = res.data;
        }
      });
    },

    // 查询角色列表
    queryRoleList() {
      this.utils.request.queryRoleListByDeptId({}, res => {
        this.roleList = res.data;
      });
    },
    //商户类型转化
    typeFormatter: function(row, column, cellValue, index) {
      if (cellValue == 1) {
        return "自营";
      } else if (cellValue == 2) {
        return "第三方商户";
      }
    },
    //商户状态转化
    statusFormatter: function(row, column, cellValue, index) {
      if (cellValue == 1) {
        return "待提交";
      } else if (cellValue == 2) {
        return "待审核";
      }  else if (cellValue == 3) {
        return "审核通过";
      } else {
        return "审核拒绝";
      }
    },
    //获取选择框数据
    selectionChange(val) {
      this.checked = val.selections;
    },
    // 显示新增界面
    handleAdd: function() {
      this.editDialogVisible = true;
      this.operation = true;
      this.queryRoleList();
      this.resetForm("dataForm");
    },
    // 显示批量审核弹窗
    reviewStatus: function() {
      if (this.checked.length < 1) {
        this.$message({ message: "请选择操作数据", type: "warning" });
        return false;
      }
      console.log(this.checked);
      this.reviewFormVisible = true;
      //this.resetForm("reviewForm");
    },
    handleClose() {
      (this.dataForm = {
        orgNumber: "",
        name: "",
        merchantType: "",
        account: "",
        password: "",
        contactName: "",
        contactMobile: ""
      }),
        this.$refs.dataForm.resetFields();
    },
    // 审核通过
    reviewSuccess() {
      let boo = false;
      this.checked.forEach(selection => {
        if (selection.status != 1) {
          boo = true;
        }
      });
      if (boo) {
        this.$message({
          message: "只能审核状态为【待审核】的用户",
          type: "error"
        });
        return;
      }
      this.$refs.reviewForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            let params = Object.assign({}, this.reviewForm);
            let this_ = this;
            params.ids = this.checked.map(item => item.id).toString();
            this.utils.request.merchantReview(params,  function(res) {
              if(res.code != "9999"){
              this_.$message({ message: "审核成功", type: "success" });
              this_.$refs["reviewForm"].resetFields();
              this_.reviewFormVisible = false;
              this_.findPage();
              }else{
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          });
        }
      });
    },
    // 新增页面
    // handleAdd: function (data) {
    //   this.$router.push({path:"/MerchantEditPage/" + 0 + '/' + 0 + '/' +2});
    // },
    // 编辑页面
    handleEdit: function(data) {
      this.$router.push({
        path:
          "/MerchantEditPage/" + data.row.id + "/" + data.row.storeId + "/" + 0
      });
    },
    // 详情页面
    handleDetail: function(data) {
      this.$router.push({
        path:
          "/MerchantEditPage/" + data.row.id + "/" + data.row.storeId + "/" + 1
      });
      // this.$router.push({path:"/MerchantEditPage",query:{cid:data.row.id,storeid:data.row.storeId,isShow:1}});
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            let params = Object.assign({}, this.dataForm);
            params.status = 2;
            var this_ = this;
            this.utils.request.editMerchantInfo(params, function(res) {
              if (res.code == "0000") {
                this_.$message({ message: "操作成功", type: "success" });

                this_.$refs["dataForm"].resetFields();

                this_.editDialogVisible = false;

                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          });
        }
      });
    },

    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },

    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.filters = {};
        this.findPage(null);
      }
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      var temp = [];

      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    //列表下载
    downloadExcel() {
      this.$confirm("确定下载列表文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.exportData(this.filters, this.filterColumns, "商户管理");
        })
        .catch(() => {});
    },
    exportData(filters, filterColumns, fileName) {
      let this_ = this
      if (filters == undefined || filters == null) {
        filters = {};
      }
      filters.start = null;
      filters.limit = null;
      this_.utils.request.queryMerchantListOther(filters, function(res) {
        const y = res.data.length;
        for (var i = 0; i < y; i++) {
          res.data[i].merchantType = this_.typeFormatter(null,null,parseInt(res.data[i].merchantType),null);
          res.data[i].status = this_.statusFormatter(null,null,parseInt(res.data[i].status),null);
        }
        exportExcel(res.data, filterColumns, fileName);
      });
    }
  },
  mounted() {
    this.initColumns();
    this.findPage();
    this.getDeptListByType();
  }
};
</script>

<style lang="scss" scoped>
</style>
